import moment from 'moment';
import {mclPrice, divisionPrice} from './utils';
/**
 * @author KD
 * @date 2018/4/9
 * @Description: 时间格式化 使用方式parseTime('{y}-{m}-{d} {h}:{i}:{s}')
 */

export function parseTime (time, cFormat) {
    if (arguments.length === 0) {
        return null;
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
    let date;
    if (typeof time === 'object') {
        date = time;
    } else {
        if (('' + time).length === 10) { time = parseInt(time) * 1000; }
        date = new Date(time);
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    };
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        if (key === 'a') { return ['一', '二', '三', '四', '五', '六', '日'][value - 1]; }
        if (result.length > 0 && value < 10) {
            value = '0' + value;
        }
        return value || 0;
    });
    return time_str;
}

export function formatTime (time, option) {
    time = +time * 1000;
    const d = new Date(time);
    const now = Date.now();

    const diff = (now - d) / 1000;

    if (diff < 30) {
        return '刚刚';
    } else if (diff < 3600) { // less 1 hour
        return Math.ceil(diff / 60) + '分钟前';
    } else if (diff < 3600 * 24) {
        return Math.ceil(diff / 3600) + '小时前';
    } else if (diff < 3600 * 24 * 2) {
        return '1天前';
    }
    if (option) {
        return parseTime(time, option);
    } else {
        return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分';
    }
}

/**
 *
 * 12345 => $12,345.00
 *
 * @param {String} symbol
 * @param {Number} decimals Decimal places
 * @param {Object} options
 */
export function currency (value, symbol, decimals, options) {
    const digitsRE = /(\d{3})(?=\d)/g;
    options = options || {};
    value = parseFloat(divisionPrice(Number(value), 100));
    if (!isFinite(value) || (!value && value !== 0)) {
        return '';
    }
    symbol = symbol != null ? symbol : '$';
    decimals = decimals != null ? decimals : 2;
    const thousandsSeparator = options.thousandsSeparator != null ? options.thousandsSeparator : ',';
    const symbolOnLeft = options.symbolOnLeft != null ? options.symbolOnLeft : true;
    const spaceBetweenAmountAndSymbol =
        options.spaceBetweenAmountAndSymbol != null
            ? options.spaceBetweenAmountAndSymbol
            : false;
    let stringified = (Math.ceil(mclPrice(value, 100)) / 100).toFixed(decimals);
    stringified = options.decimalSeparator
        ? stringified.replace('.', options.decimalSeparator)
        : stringified;
    const _int = decimals ? stringified.slice(0, -1 - decimals) : stringified;
    const i = _int.length % 3;
    const head =
        i > 0 ? _int.slice(0, i) + (_int.length > 3 ? thousandsSeparator : '') : '';
    const _float = decimals ? stringified.slice(-1 - decimals) : '';
    symbol = spaceBetweenAmountAndSymbol
        ? symbolOnLeft
            ? symbol + ' '
            : ' ' + symbol
        : symbol;
    symbol = symbolOnLeft
        ? symbol +
        head +
        _int.slice(i).replace(digitsRE, '$1' + thousandsSeparator) +
        _float
        : head +
        _int.slice(i).replace(digitsRE, '$1' + thousandsSeparator) +
        _float +
        symbol;
    const sign = value < 0 ? '-' : '';
    return sign + symbol;
}

/**
 *
 *
 * @param {String} property
 * @Description {{ msg | placeholder('Text if msg is missing') }} // '' => 'Text if msg is missing'
 */
export function placeholder (input, property) {
    return (input === undefined || input === '' || input === null) ? property : input;
}

/**
 *
 *
 * @param {Number} length
 * @Description {{ msg | truncate(10) }} // 'lorem ipsum dolor' => 'lorem ipsu...'
 */
export function truncate (value, length) {
    length = length || 15;
    if (!value || typeof value !== 'string') { return ''; }
    if (value.length <= length) { return value; }
    return value.substring(0, length) + '...';
}

/**
 * Limit filter for arrays
 *
 * @param {Number} n
 * @param {Number} offset (Decimal expected)
 */
export function limitBy (arr, n, offset) {
    offset = offset ? parseInt(offset, 10) : 0;
    return typeof n === 'number'
        ? arr.slice(offset, offset + n)
        : arr;
}

export function truncateName (value, length = 5) {
    const arr = value.split(',');
    let input;
    input = value;
    if (arr.length > length) {
        input = arr.slice(0, length).join(',') + '等' + arr.length + '国家/地区';
    }
    return input;
}

export function utcFormat (time, cFormat = 'YYYY-MM-DD HH:mm:ss', utcOffset) {
    if (arguments.length === 0) {
        return null;
    }
    if (time === undefined || time === null || time === '') {
        return null;
    }
    return moment(time).utcOffset(+utcOffset).format(cFormat);
}
